import DlyAdminMenu from '../../model/dlyadminmenu'
import DlyAdminShopWhite from '../../model/dlyadminshopwhite'
import ApiError from '../../error/ApiError'
import ApiErrorNames from '../../error/ApiErrorNames'
class MenuController {
	static async add(ctx) {
		const requestBody = ctx.request.body
		// 新增菜单
		// 删除_id
		if (requestBody.hasOwnProperty('_id')) delete requestBody._id
		const menu = await DlyAdminMenu.create(requestBody)
		ctx.body = menu
		// ctx.body = '新增菜单'
	}
	static async list(ctx) {
		// 获取菜单列表
		const menuList = await DlyAdminMenu.find({})
		const foterdata = JSON.parse(JSON.stringify(menuList))

		if (menuList) {
			ctx.body = buildTree(foterdata, '0')
			return
		}
		throw new ApiError(ApiErrorNames.MenuListFail)
	}
	static async update(ctx) {
		//编辑菜单
		const _id = ctx.request.query._id
		const requestBody = ctx.request.body
		if (!_id) {
			throw new ApiError(ApiErrorNames.MenuUpdateFail)
		}
		if (requestBody.hasOwnProperty('_id')) delete requestBody._id
		const menu = await DlyAdminMenu.findByIdAndUpdate(_id, requestBody)
		if (menu) {
			ctx.body = menu
			return
		}
		throw new ApiError(ApiErrorNames.MenuUpdateFail)
	}

	static async deleted(ctx) {
		// 删除 同时删除子项
		const _id = ctx.request.query._id
		if (!_id) {
			throw new ApiError(ApiErrorNames.MenuDeleteFail)
		}
		const menu = await DlyAdminMenu.findByIdAndRemove(_id)

		const menuList = await DlyAdminMenu.find({ pid: menu._id })
		if (menuList) {
			menuList.forEach(async (item) => {
				await DlyAdminMenu.findByIdAndRemove(item._id)
			})
		}
		// 还需要删除其他关联的数据
		// 角色项等

		if (menu) {
			ctx.body = menu
			return
		}
		throw new ApiError(ApiErrorNames.MenuDeleteFail)
	}

	static async getCurrentUserPermissions(ctx) {
		const { roleName } = ctx.request.header.jwtuserinfo
		if (roleName === 'admin') {
			const menuList = await DlyAdminMenu.find({})
			const foterdata = JSON.parse(JSON.stringify(menuList))

			if (menuList) {
				ctx.body = buildTree(foterdata, '0')
				return
			}
			throw new ApiError(ApiErrorNames.MenuListFail)
		}
	}
	static async addShopWhite(ctx) {
		console.log(ctx.request.body)
		if (
			!ctx.request.body ||
			!ctx.request.body.shopName ||
			!ctx.request.body.shopId
		) {
			throw new ApiError(ApiErrorNames.NoParamsData)
		}
		const findOneShop = await DlyAdminShopWhite.findOne({
			shopId: ctx.request.body.shopId,
		})
		if (findOneShop) {
			throw new ApiError(ApiErrorNames.ShopWhiteExist)
		}
		const addData = {
			shopName: ctx.request.body.shopName,
			shopId: ctx.request.body.shopId,
		}
		const shopWhite = new DlyAdminShopWhite(addData)
		const savedata = await shopWhite.save()
        upDataWhiteList()
		ctx.body = savedata
	}
	static async shopWhiteList(ctx) {
		// 获取白名单列表
		const { pageSize = 20, page = 1 } = ctx.query

		const shopWhiteList = await DlyAdminShopWhite.find({})
			.limit(pageSize * 1)
			.skip((page - 1) * pageSize)

		const total = await DlyAdminShopWhite.countDocuments({})
		ctx.body = {
			list: shopWhiteList,
			total,
		}
	}
	static async rmShopWhite(ctx) {
		// 删除白名单
		if (!ctx.params.id) {
			throw new ApiError(ApiErrorNames.NoParamsData)
		}
		try {
			const id = ctx.params.id
			const result = await DlyAdminShopWhite.deleteOne({ _id: id })
			if (result.deletedCount === 0) {
				throw new ApiError(ApiErrorNames.NoData)
			}
            upDataWhiteList()
			ctx.body = 'ok'
		} catch (error) {
			throw new ApiError(ApiErrorNames.UnknownError)
		}
	}
}
function buildTree(arr, parentId) {
	let tree = []
	arr.forEach((item) => {
		if (item.pid === parentId) {
			let children = buildTree(arr, item._id)
			if (children.length > 0) {
				item.children = children
			}
			tree.push(item)
		}
	})
	return tree
}

async function upDataWhiteList() {
	const shopWhiteList = await DlyAdminShopWhite.find({}).limit(1000).skip(0)
    global.WhiteList = global.WhiteListOl

    if(shopWhiteList.length > 0) {
       const shopWList = shopWhiteList.map(res => {
            return res.shopId
        })
        const mergedArray = Array.from(new Set([...global.WhiteListOl, ...shopWList]))
        global.WhiteList = mergedArray
        return
    }
}

export default MenuController
